package com.imc.platform.base.user.security;

import com.imc.core.config.mvc.MvcConfigurerAdapter;
import com.imc.core.config.websecurity.WebSecurityProperty;
import com.imc.core.config.websecurity.WebsecurityConfig;
import com.imc.core.utils.RandomValidateCodeUtil;
import com.imc.platform.base.user.myexception.ValidateCodeException;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by tanweiping on 2018/8/6.
 */
/*
* 类描述：验证码处理器
* 开发者：tanweiping
* 创建日期：2018/8/7 10:37
*/
@EqualsAndHashCode(callSuper = false)
@Slf4j
@Data
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {

    @Autowired
    MvcConfigurerAdapter mvcConfigurerAdapter;

    @Autowired
    WebSecurityProperty webSecurityProperty;

    @Autowired
    WebsecurityConfig websecurityConfig;


    private AuthenticationFailureHandler authenticationFailureHandler;

    /*
    * tanweiping  2018/8/7 10:37
    * 方法描述：验证码校验
    */
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if(StringUtils.equals(mvcConfigurerAdapter.getContextPath()+webSecurityProperty.getLoginProcessingUrl(), httpServletRequest.getRequestURI())
                && StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) {
            try {
                // 1. 进行验证码的校验
                validate(httpServletRequest);
            } catch (ValidateCodeException e) {
                // 2. 如果校验不通过，调用SpringSecurity的校验失败处理器
                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
                return;
            }
        }
        // 3. 校验通过，就放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private void validate(HttpServletRequest request){
        String code = request.getParameter("verityCode");
        if (StringUtils.isNotEmpty(code)){
            Object sessionCode = request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
            if (sessionCode!=null&& sessionCode.equals(code)){
                log.info("验证码通过");
            }else {
                throw new ValidateCodeException("验证码错误");
            }
        }
    }

}